//
//  FaceViewController.m
//  TestAispeech
//
//  Created by shaowei on 13-9-7.
//  Copyright (c) 2013年 LianZhan. All rights reserved.
//

#import "FaceVerifyViewController.h"
#import "ParamsConfig.h"
#import "FaceManager.h"
#import "MBProgressHUD.h"
#import "FaceImageHandle.h"
#import "FaceSetPwdViewController.h"

@interface FaceVerifyViewController ()

@end

@implementation FaceVerifyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    if (![FaceManager isHavePersonInfo]) {
        //还未设置过人脸识别的话，跳转到设置界面
        ALERT_VIEW(@"您还未设置过人脸密码", @"开始设置人脸密码");
        [self performSegueWithIdentifier:@"FaceCreateViewController" sender:nil];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    Block_release(_completeHandle);
    [_btnOfImage release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setBtnOfImage:nil];
    [super viewDidUnload];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __block FaceVerifyViewController *tempSelf = self;
    if ([segue.identifier isEqualToString:@"FaceCreateViewController"]) {
        FaceSetPwdViewController *createVC = (FaceSetPwdViewController *)segue.destinationViewController;
        [createVC setCompleteBlock:^(PersonModel *model,BOOL success){
            if (success) {
                //保存人物信息
                [FaceManager savePersonInfo:model];
                //回到前台主线程执行
                dispatch_async(dispatch_get_main_queue(), ^{
                    [tempSelf.presentedViewController dismissModalViewControllerAnimated:YES];
                }) ;
            }
        }];
    }
}

#pragma mark - action

- (IBAction)actionTakePicture:(id)sender {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;//前置摄像头
    [self presentModalViewController:imagePicker animated:YES];
    [imagePicker release];
}

#pragma mark Function - Private

- (void)verifyPersonImage:(UIImage *)imageToDisplay{
    //异步后台线程运行
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        FaceppResult *resultOfDetection = [[FaceppAPI detection] detectWithURL:nil
                                                                   orImageData:UIImageJPEGRepresentation(imageToDisplay, 0.8f)
                                                                          mode:FaceppDetectionModeNormal
                                                                     attribute:FaceppDetectionAttributeNone];
        if (resultOfDetection.success) {
            //人脸对比
            NSString *faceID = [[resultOfDetection content][@"face"] lastObject][@"face_id"];
            FaceppResult *resultOfRecognition = [[FaceppAPI recognition] verifyWithFaceId:faceID
                                                                              andPersonId:[FaceManager getPersonInfo].person_id
                                                                             orPersonName:[FaceManager getPersonInfo].person_name
                                                                                    async:NO];
            BOOL person_same = [[resultOfRecognition content][@"is_same_person"] boolValue];
            CGFloat same_confidence = [[resultOfRecognition content][@"confidence"] floatValue];
            
            //相似度same_confidence（0～100），可以根据识别的精确度来调整,这里取1%，（即有1%的可能也算通过）
            BOOL resultOfVerify = resultOfRecognition.success && person_same && (same_confidence >= 1.0f);
            if (resultOfVerify) {
                //回到前台主线程执行
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.btnOfImage setImage:imageToDisplay forState:UIControlStateNormal];
                }) ;
                ALERT_VIEW(@"恭喜!",@"您的头像验证通过!");
            }else{
                ALERT_VIEW(@"头像验证失败",@"您和系统用户可能不是同一个人。");
            }
            
            //回调
            if (_completeHandle) {
                _completeHandle(resultOfVerify);
            }
            
        }else{
            ALERT_VIEW(@"人脸识别失败，请重新拍摄头像",nil);
        }
        
        //回到前台主线程执行
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:NO];
        }) ;
        
    });
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    UIImage *sourceImage = info[UIImagePickerControllerOriginalImage];
    UIImage *imageToDisplay = [FaceImageHandle fixOrientation:sourceImage];
    
    //开始验证
    [self verifyPersonImage:imageToDisplay];
    
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissModalViewControllerAnimated:YES];
}

@end
